package com.yq.realm;

import com.yq.domain.User;
import com.yq.servicce.UserService;
import com.yq.vo.ActiveUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: yangQ
 * @Date: 2020/11/24 11:02
 * @Description:
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 做认证  --就是登陆
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户的登录名
        String phone = authenticationToken.getPrincipal().toString();
        //根据电话查询用户是否存在
        User user = userService.queryUserByPhone(phone);
        if(null!=user){//说明用户存在，但是密码可能不正确
            //组装存放到redis里面的对象
            ActiveUser activeUser = new ActiveUser();
            activeUser.setUser(user);
            //得到密码加密的盐
            ByteSource salt = ByteSource.Util.bytes(user.getSalt());
            //匹配密码

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser,user.getPassword(),salt,this.getName());
            return info;
        }else {
            return null;
        }
    }

    /**
     * 做授权  --登陆成功之后判断用户是否有某个菜单或按钮的权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activeUser= (ActiveUser) principals.getPrimaryPrincipal();//身份得到的就是上一个方法的返回值的值 第一个参数activerUser
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        return info;
    }


}
